import { pagedCredit } from '@/services/payment/credit_api';
import { PageContainer, ProTable, type ActionType, type ProColumns } from '@ant-design/pro-components';
import {  Button, message } from 'antd';
import {
  PlusOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { FormattedMessage, useIntl } from '@umijs/max';
import React, { useRef, useState, useEffect } from 'react';
import { CustomerAddressVo } from '../constants';
import AddForm from './components/AddForm';
import { CreditPageRespVO } from './types';
import { get_map } from '@/services/system_api';
import { safeDateFormat } from '@/utils/time';
import { formatToLocalTime,toUTC } from '@/utils/time';


const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [loading, setLoading] = useState(false);
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<CustomerAddressVo>();
  const [selectedRowsState, setSelectedRows] = useState<CustomerAddressVo[]>([]);
  const [editRow, setEditRow] = useState<CustomerAddressVo>();



  const [enums, setEnums] = useState<{
    creditType: Record<string, any>;
    status: Record<string, any>;
  }>({ creditType: {}, status: {} });

  useEffect(() => {
    const fetchEnums = async () => {
      try {
        const [creditTypeRes, statusRes] = await Promise.all([
          get_map("elm_credit_type"),
          get_map("elm_credit_status")
        ]);

        setEnums({
          creditType: creditTypeRes.data.reduce((acc, { label, value }) => {
            acc[value] = { text: label };
            return acc;
          }, {}),
          status: statusRes.data.reduce((acc, { label, value }) => {
            acc[value] = { text: label };
            return acc;
          }, {})
        });
      } catch (error) {
        console.error('Failed to load enums:', error);
        message.error('Failed to load enums');
      }
    };

    fetchEnums();
  }, []);

  const handleApprove = (id: string) => {
    // 审核逻辑
  };

  const handleViewDetail = (id: string) => {
    // 查看详情逻辑
  };
  const intl = useIntl();
  const columns: ProColumns<CreditPageRespVO>[] = [
  {
    title: intl.formatMessage({ id: 'pages.customer.credit.columns.customerCode' }),
    dataIndex: 'customerCode',
    width: 120,
  },
  {
    title: intl.formatMessage({ id: 'pages.customer.credit.columns.customerName' }),
    dataIndex: 'customerName',
    width: 150,
    search: false,
  },
  {
    title: intl.formatMessage({ id: 'pages.customer.credit.columns.creditCode' }),
    dataIndex: 'creditCode',
    width: 180,
  },
  {
    title: intl.formatMessage({ id: 'pages.customer.credit.columns.creditType' }),
    dataIndex: 'creditType',
    width: 120,
    valueEnum: enums.creditType,
  },
  {
    title: intl.formatMessage({ id: 'pages.customer.credit.columns.creditAmount' }),
    dataIndex: 'creditAmount',
    width: 120,
    render: (text) => `¥${text?.toLocaleString()}`,
    search: false,
    sorter: true,
  },
  {
    title: intl.formatMessage({ id: 'pages.customer.credit.columns.creditDuration' }),
    dataIndex: 'creditDuration',
    width: 100,
    search: false,
  },
  {
    title: intl.formatMessage({ id: 'pages.customer.credit.columns.status' }),
    dataIndex: 'status',
    width: 120,
    filters: true,
    valueEnum: enums.status,
  },
  {
    title: (
      <FormattedMessage
        id="pages.createTime"
        defaultMessage="Create Time"
      />
    ),
    dataIndex: 'createTime',
    sorter: true,
    valueType: 'dateRange',
    hideInForm: true,
    search: {
      transform: (value) => ({
        startTime: toUTC(value[0]),
        endTime: toUTC(value[1],true)
      })
    },
    render: (_, record) => {
      return formatToLocalTime(record.createTime);
    }
  },
  {
    title: intl.formatMessage({ id: 'pages.customer.credit.columns.creditTime' }),
    dataIndex: 'creditTime',
    width: 180,
    render: (text) => safeDateFormat(text),
    search: false,
  },
  {
    title: intl.formatMessage({ id: 'pages.customer.credit.columns.dueTime' }),
    dataIndex: 'dueTime',
    width: 180,
    render: (text) => safeDateFormat(text),
    search: false,
  },
];


  return (
    <PageContainer title={false}>
      <ProTable<CreditPageRespVO, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.cust.address.list',
          defaultMessage: 'Shipper Address List',
        })}
        actionRef={actionRef}
        loading={loading}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              //新建
              handleModalOpen(true);
            }}
          >
            <PlusOutlined />
            <FormattedMessage id="pages.credit.new" defaultMessage="New" />
          </Button>,
        ]}
        request={pagedCredit}
        columns={columns}
     scroll={{ x: 'max-content' }}
      />


      <AddForm
        // width="40%"
        visible={createModalOpen}
        // onOpenChange={handleModalOpen}
        onCancel={async () => { handleModalOpen(false) }}
        onSuccess={function (): void {
          handleModalOpen(false)
          setCurrentRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      >
      </AddForm>

      <AddForm
        visible={updateModalOpen}
        values={currentRow}
        onCancel={async () => {
          handleUpdateModalOpen(false);
          setCurrentRow(undefined);
          setEditRow(undefined);
        }}
        onSuccess={function (): void {
          handleUpdateModalOpen(false)
          setCurrentRow(undefined);
          setEditRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      >
      </AddForm>
    </PageContainer>
  );
};

export default TableList;
